package com.zhuxiaomei.service.impl;

import com.zhuxiaomei.dto.ws.WSResult;
import com.zhuxiaomei.entity.msg.CoupleBindMessage;
import com.zhuxiaomei.mapper.CoupleBindMessageMapper;
import com.zhuxiaomei.service.MessageService;
import com.zhuxiaomei.utils.MessageUtils;
import jakarta.annotation.Resource;
import jakarta.websocket.Session;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author hxm
 * @date 2024/12/24 12:30
 * @description
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    private CoupleBindMessageMapper coupleBindMessageMapper;


    @Override
    public void handleCoupleBind(Session session, WSResult wsResult) {
        CoupleBindMessage msg = CoupleBindMessage.builder()
                .type(wsResult.getType())
                .fromAccount(wsResult.getFrom())
                .toAccount(wsResult.getTo())
                .status("1")
                .data(wsResult.getMessage().toString())
                .build();
        if (msg.getType().equals("5000")){
            int row = coupleBindMessageMapper.selectCount(msg);
            if (row == 0){
                coupleBindMessageMapper.insertMessage(msg);
            }
        }
        if (session == null){

        }else {
            String message = MessageUtils.getMessage(wsResult);
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public List<CoupleBindMessage> selectMessage(String fromAccount, String toAccount, String status) {
        CoupleBindMessage msg = CoupleBindMessage.builder().fromAccount(fromAccount).toAccount(toAccount).status(status).build();
        List<CoupleBindMessage> msgs = coupleBindMessageMapper.select(msg);
        return msgs;
    }
}
